package com.taojie.graduation.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taojie.graduation.domain.Logistics;
import com.taojie.graduation.domain.Store;
import com.taojie.graduation.mapper.LogisticsMapper;
import com.taojie.graduation.mapper.StoreMapper;
import com.taojie.graduation.service.api.LogisticsService;
import com.taojie.graduation.utils.PageResult;
import com.taojie.graduation.utils.Result;
import com.taojie.graduation.utils.ResultCode;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName LogisticsServiceImpl
 * @Description TODO
 * @Author Chole
 * @Date 2020/4/20 13:07
 */
@Service
public class LogisticsServiceImpl implements LogisticsService {
    @Resource
    LogisticsMapper logisticsMapper;

    @Resource
    StoreMapper storeMapper;

    @Override
    public Result findLogisticsPage(int page, int size) {
        Page<Logistics> userPage = new Page<>(page, size);
        Page<Logistics> logisticsPage1 = logisticsMapper.selectPage(userPage, null);
        // 根据id排序
        List<Logistics> collect = logisticsPage1.getRecords().stream().sorted(Comparator.comparing(Logistics::getId)).collect(Collectors.toList());
        if (!(logisticsPage1.getRecords().size() > 0)) {
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS, new PageResult<Logistics>(logisticsPage1.getTotal(), collect));
    }

    @Override
    public Result findLogisticsById(int id) {
        if (id < 0) {
            return Result.INPUT_ERROR();
        }
        Logistics logistics = logisticsMapper.selectById(id);
        if (ObjectUtils.isEmpty(logistics)) {
            return new Result(ResultCode.NOT_FOUND);
        }
        return new Result(ResultCode.SUCCESS, logistics);
    }

    @Override
    public int addLogistics(String carAddress, int storeId, int orderId) {
        if (storeId <= 0) {
            return -1;
        }
        Store store = storeMapper.selectById(storeId);
        if (ObjectUtils.isEmpty(store)) {
            return -1;
        }
        Logistics logistics = new Logistics();
        logistics.setStart(store.getAddress());
        logistics.setEnd(carAddress);
        logistics.setTime(2);
        logistics.setOrderId(orderId);
        logistics.setDelivery(0);

        return logisticsMapper.insert(logistics);
    }
}
